"""
rest请求客户端，使用连接池请求
"""
import gzip

import requests
from requests import Response, HTTPError

class HttpClient:

    @staticmethod
    def get(url, params={}, headers={}, timeout=120):
        resp = requests.get(url,params=params, headers=headers, timeout=timeout)
        return HttpClient.wrapper_resp(resp)

    @staticmethod
    def post(url, headers = {}, data = {}, body = None, timeout=120, json = True):
        resp = requests.post(url, data=data, headers=headers, json=body, timeout=timeout)
        if json:
            return HttpClient.wrapper_resp(resp)
        return resp

    @staticmethod
    def wrapper_resp(resp : Response):
        if not resp or resp.status_code != 200:
            raise HTTPError(f"网络请求失败：{resp.url},响应为{resp.text}")
        return resp.json()

    @staticmethod
    def get_request_data(request):
        """
        获取传入的data内容
        :return:
        """
        if 'gzip' in [x.strip() for x in request.headers.get('Content-Encoding', '').split(',') if x.strip()]:
            gzip_content = gzip.decompress(request.data)
            return gzip_content
        return request.data.decode('utf-8')

    @staticmethod
    def get_request_ip(request):
        # 获取 X-Forwarded-For HTTP 头部信息
        x_forwarded_for = request.headers.getlist('X-Forwarded-For')
        if x_forwarded_for:
            # 返回 X-Forwarded-For 列表中的第一个 IP 地址，通常是客户端的真实 IP
            return x_forwarded_for[0]
        else:
            # 如果没有 X-Forwarded-For 头部，则返回 remote_addr，即直接客户端的 IP
            return request.remote_addr



